<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var deelyNestedObj = {
      a: {
        b: {
          c: {
            d: 123
          }
        }
      }
    };


    function safeGet(target, keyStr, defaultValue) {
      let keys = keyStr.replace(/\s*/g, '').replace(/\.\./g, '.')
      // console.log(keys);
      let keysArr = keys.split('.')

      let obj
      function walk(targetObj, Arr) {
        obj = targetObj[Arr[0]]
        // console.log(obj);
        if (!obj) return obj
        Arr.shift()
        // console.log(Arr);
        if (Arr.length == 0) return obj;
        walk(obj, Arr)
        return obj || defaultValue
      }
      console.log(walk(target, keysArr));
    }

    safeGet(deelyNestedObj, 'a.b.c.d', 'Alipay') // 123
    safeGet(deelyNestedObj, ' a. b..c..d ') // 123
    safeGet(deelyNestedObj, 'a.b.c1.d') // undefined
    safeGet(deelyNestedObj, 'a.b.c1.d', 'Alipay') // "Alipay"
    safeGet(deelyNestedObj, 'a.b.c.d.e.f.g.h') // undefined
  </script>
</body>

</html>